package cn.com.cifi.mars.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.dto.PositionGroupAuthDto;
import cn.com.cifi.mars.bean.vo.sys.rsp.PositionGroupAuthVo;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.IsDisableEnum;
import cn.com.cifi.mars.constant.IsSuccessEnum;
import cn.com.cifi.mars.constant.JobDefinitionTypeEnum;
import cn.com.cifi.mars.constant.LogEventEnum;
import cn.com.cifi.mars.constant.LogSrcEnum;
import cn.com.cifi.mars.constant.LogTypeEnum;
import cn.com.cifi.mars.entity.common.IdmPositionGroup;
import cn.com.cifi.mars.mapper.mars.IdmPositionGroupMapper;
import cn.com.cifi.mars.service.IdmPositionGroupService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.util.BasicAuthClient;
import cn.com.cifi.mars.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class PositionGroupServiceImpl extends ServiceImpl<IdmPositionGroupMapper, IdmPositionGroup> implements IdmPositionGroupService {

	@Autowired
	private IdmPositionGroupMapper idmPositionGroupMapper;
	
	@Autowired
	private SysLogService sysLogService;
	
	@Value("${host}")
	private String host;
	
	@Value("${port_idm}")
	private String port_idm;
	
	@Value("${api_name}")
	private String api_name;
	
	@Value("${api_key}")
	private String api_key;
	
	@Override
	public List<String> getJobDefinitionsIdList() {
		return idmPositionGroupMapper.selectJobDefinitionsIdList();
	}

	/**
	 * 岗位组权限分页
	 */
	@Override
	public PositionGroupAuthVo queryPotGroupAuthPage(String current, String pageSize, String jobDefinitionsName,
			String jobDefinitionsId) {
		if(jobDefinitionsName.equals(Constants.PLEASE_CHOOSE)) {
			jobDefinitionsName="";
		}
		if(jobDefinitionsId.equals(Constants.PLEASE_CHOOSE)) {
			jobDefinitionsId="";
		}
		Page<PositionGroupAuthDto>pageDto=new Page<PositionGroupAuthDto>();
		//参数当前页
		pageDto.setCurrent(Integer.parseInt(current));
		//参数每页数量
		pageDto.setSize(Integer.parseInt(pageSize));
		List<PositionGroupAuthDto>list=idmPositionGroupMapper.selectPositionGroupAuthPage(pageDto, jobDefinitionsName, jobDefinitionsId);
		list.forEach(x->{
			String is_enable = x.getJobDefinitionStatus();
			String effective = "";
			if (is_enable.equals(IsDisableEnum.NO.getKey() + "")) {
				effective = "有效";
			} else {
				effective = "无效";
			}
			// 岗位定义类型 1-行政岗 2-业务岗
			String jobDefinitionType=x.getJobDefinitionType();
			if (is_enable.equals(JobDefinitionTypeEnum.ADMINISTRATIVEPOST.getKey() + "")) {
				jobDefinitionType = JobDefinitionTypeEnum.ADMINISTRATIVEPOST.getValue() + "";
			} else {
				jobDefinitionType = JobDefinitionTypeEnum.BUSINESSPOST.getValue() + "";
			}
			String authMode=x.getAuthMode();
			if(authMode.equals("1")) {
				authMode="自动授权";
			}else {
				authMode="";
			}
			x.setAuthMode(authMode);
			x.setJobDefinitionStatus(effective);
			x.setJobDefinitionType(jobDefinitionType);
		});
		//分页和list
		PositionGroupAuthVo vo=new PositionGroupAuthVo();
		vo.setCurrent(pageDto.getCurrent());
		vo.setPages(pageDto.getPages());
		vo.setPageSize(pageDto.getSize());
		vo.setTotal(pageDto.getTotal());
		vo.setList(list);
		return vo;
	}

	/**
	 * 查询岗位组存在供销存的数据
	 */
	@Override
	public List<String> getPositionGroupName() {
		return idmPositionGroupMapper.selectJobDefinitionsNameList();
	}	
	
	/**
	 * 增量同步岗位组
	 */
	@Transactional
	@Override
	public String syncPositionGroup(String timestamp, String cookie,String jobGroupNum, List<String> groupIds) {
		BasicAuthClient bac = new BasicAuthClient();
		String url = host+"/idm/jobDefs/query";
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		if("0".equals(cookie)||"null".equals(cookie)) {
			
		}else {
			String[] cookies=cookie.split(",");
			cookie=BasicAuthClient.encryptionCookie(cookies);
		}
		String jsonParam = "{\"esbInfo\":{\"instId\":\"\",\"requestTime\":\""+requestTime+"\"},\"requestInfo\":{\"timestamp\":\""+timestamp+"\",\"cookie\":"+"\""+cookie+"\""+",\"basedn\":\"ou=jobdefinitions,ou=JobPortfolios,dc=bizenit,dc=com\",\"filter\":\"(cn="+jobGroupNum+")\"}}";
		String result = bac.post(url,jsonParam,api_name,api_key);
		JSONObject jsonObject=JSONObject.parseObject(result);
		JSONObject esbInfo=jsonObject.getJSONObject("esbInfo");
		String returnMsg=esbInfo.getString("returnMsg");
		log.info("######### 同步岗位组数据请求参数："+jsonParam);
		if(returnMsg.equals("success")) {
			JSONObject resultInfo=jsonObject.getJSONObject("resultInfo");
			JSONArray results=(JSONArray) resultInfo.get("results");
			JSONArray cookies=(JSONArray) resultInfo.get("cookie");
			List<IdmPositionGroup>list=new ArrayList<>();
			for (int i = 0; i < results.size(); i++) {
				String jobDefinitionsDescription=results.getJSONObject(i).getString("jobDefinitionsDescription");
				String z9121zn=results.getJSONObject(i).getString("z9121zn");
				String z9121xl=results.getJSONObject(i).getString("z9121xl");
				String z9121znt=results.getJSONObject(i).getString("z9121znt");
				String z9121xlt=results.getJSONObject(i).getString("z9121xlt");
				String jobDefinitionsName=results.getJSONObject(i).getString("jobDefinitionsName");
				String jobDefinitionType=results.getJSONObject(i).getString("jobDefinitionType");
				String z9121cjt=results.getJSONObject(i).getString("z9121cjt");
				String firmcoding=results.getJSONObject(i).getString("firmcoding");
				String sapjobdefId=results.getJSONObject(i).getString("sapjobdefId");
				String jobDefinitionsId=results.getJSONObject(i).getString("jobDefinitionsId");
				String jobDefinitionStatus=results.getJSONObject(i).getString("jobDefinitionStatus");
				String z9121cj=results.getJSONObject(i).getString("z9121cj");

				IdmPositionGroup pos=new IdmPositionGroup();
				pos.setJobDefinitionsDescription(jobDefinitionsDescription.replace("null", ""));
				pos.setZ9121zn(z9121zn.replace("null", ""));
				pos.setZ9121xl(z9121xl.replace("null", ""));
				pos.setZ9121znt(z9121znt.replace("null", ""));
				pos.setZ9121xlt(z9121xlt.replace("null", ""));
				pos.setJobDefinitionsName(jobDefinitionsName.replace("null", ""));
				pos.setJobDefinitionType(jobDefinitionType.replace("null", ""));
				pos.setZ9121cjt(z9121cjt.replace("null", ""));
				pos.setFirmcoding(firmcoding.replace("null", ""));
				pos.setSapjobdefId(sapjobdefId.replace("null", ""));
				pos.setJobDefinitionsId(jobDefinitionsId.replace("null", ""));
				pos.setJobDefinitionStatus(jobDefinitionStatus.replace("null", ""));
				pos.setZ9121cj(z9121cj.replace("null", ""));
				list.add(pos);
			}
			List<IdmPositionGroup> saveList =new ArrayList<>();
			List<IdmPositionGroup> updateList =new ArrayList<>();
			for (IdmPositionGroup up : list) {
				if(groupIds.contains(up.getJobDefinitionsId())) {
					updateList.add(up);
				}
			}
			for (IdmPositionGroup sa : list) {
				if(!groupIds.contains(sa.getJobDefinitionsId())) {
					saveList.add(sa);
				}
			}
			this.saveBatch(saveList);
			idmPositionGroupMapper.updateList(updateList);
			
			String addStr = getPositionGroup(saveList);
            String updateStr = getPositionGroup(updateList);
            saveLog("增量同步IDM岗位组信息","请求参数：" + url+jsonParam + ";响应数据：新增岗位组：" + addStr+"&&更新岗位组："+updateStr);
			if(cookies!=null) {
				String ck=cookies.toString().replace("[","").replace("]","");
				syncPositionGroup(timestamp, ck,jobGroupNum, groupIds);
			}
			return "响应数据：新增岗位组："+addStr+"&&更新岗位组："+updateStr;
		}else {
			return returnMsg;
		}
	}

	private String getPositionGroup(List<IdmPositionGroup> saveList) {
		StringBuilder sb = new StringBuilder();
    	for(IdmPositionGroup org : saveList) {
    		sb.append(org.getJobDefinitionsId()).append("~").append(org.getJobDefinitionsName()).append(";");
		}
		return sb.toString();
	}
	
	private void saveLog(String title,String content) {
        SysLogBO bo = new SysLogBO();
        bo.setEvent(LogEventEnum.TIMERTASK);
        bo.setSource(LogSrcEnum.SYS);
        String hostAddr =WebUtils.getLocalIP();
        bo.setIp(hostAddr);
        bo.setModule("同步IDM岗位组信息");
        bo.setTitle(title);
        bo.setContent(content);
        bo.setType(LogTypeEnum.ONE.getKey());
        bo.setIsSuccess(IsSuccessEnum.SUCCESS.getKey());
        sysLogService.add(bo,Constants.SYS);
     }
}
